//
//  ChatModel.m
//  UUChatTableView
//
//  Created by shake on 15/1/6.
//  Copyright (c) 2015年 uyiuyao. All rights reserved.
//

#import "ChatModel.h"

#import "UUMessage.h"
#import "UUMessageFrame.h"
#import <JMessage/JMessage.h>

@implementation ChatModel

- (void)populateRandomDataSource {
    
    self.dataSource = [NSMutableArray array];
    [self.dataSource addObjectsFromArray:[self additems:0]];
}

- (void)addRandomItemsToDataSource:(NSInteger)number{
    
    for (int i=0; i<number; i++) {
        [self.dataSource insertObject:[[self additems:1] firstObject] atIndex:0];
    }
}

- (void)recountFrame
{
	[self.dataSource enumerateObjectsUsingBlock:^(UUMessageFrame * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
		obj.message = obj.message;
	}];
}

// 添加自己的item
- (void)addSpecifiedItem:(NSDictionary *)dic
{
    UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
    UUMessage *message = [[UUMessage alloc] init];
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dic];

    [message setWithDict:dataDic];
    [message minuteOffSetStart:previousTime end:dataDic[@"strTime"]];
    messageFrame.showTime = message.showDateLabel;
    [messageFrame setMessage:message];
    
    if (message.showDateLabel) {
        previousTime = dataDic[@"strTime"];
    }
    [self.dataSource addObject:messageFrame];
}

// 添加聊天item（一个cell内容）
static NSString *previousTime = nil;
- (NSArray<UUMessageFrame *> *)additems:(NSInteger)number
{
    
    NSMutableArray<UUMessageFrame *> *result = [NSMutableArray array];

    NSMutableArray * arrList = [[NSMutableArray alloc] init];

    [arrList addObjectsFromArray:[[[_conversation messageArrayFromNewestWithOffset:@0 limit:@(number)] reverseObjectEnumerator] allObjects]];
    
//    NSLog(@"arrlist===%@",arrList);
//    for (JMSGMessage * message in arrList) {
//
//        if (message.contentType == 1 || message.contentType == 2 || message.contentType == 3) {
//
//            [self.jmessageArray addObject:message];
//        }
//    }
//    self.jmessageArray = arrList;
    self.jmessageArray = [NSMutableArray array];
    for (NSInteger i=0; i< [arrList count]; i++) {
        
        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
        JMSGMessage * Jmessage = [arrList objectAtIndex:i];

        NSInteger from = Jmessage.isReceived;
        NSUInteger contentType = Jmessage.contentType;
        if (contentType == 1) {
            [self.jmessageArray addObject:Jmessage];
            // 文本消息
            JMSGAbstractContent *content = Jmessage.content;
            
            JMSGTextContent *textContent = (JMSGTextContent *)content;
            
            [dict setObject:textContent.text forKey:@"strContent"];
            
            NSString * timeStr = [NSString stringWithFormat:@"%@",Jmessage.timestamp];
            NSTimeInterval interval    = [timeStr doubleValue] / 1000;
            NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
            JMSGUser * user = Jmessage.fromUser;
            
            if (user.nickname) {
                [dict setObject:user.nickname forKey:@"strName"];
            }
            
            [dict setObject:@(from) forKey:@"from"];
            [dict setObject:@(1) forKey:@"type"];
            [dict setObject:[date description] forKey:@"strTime"];
            [dict setObject:user forKey:@"user"];
            
            NSDictionary * dataDic = dict.copy;
            
            UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
            UUMessage * message = [[UUMessage alloc] init];
            [message setWithDict:dataDic];
            [message minuteOffSetStart:previousTime end:dataDic[@"strTime"]];
            messageFrame.showTime = message.showDateLabel;
            [messageFrame setMessage:message];
            
            if (message.showDateLabel) {
                previousTime = dataDic[@"strTime"];
            }
            [result addObject:messageFrame];
            
        }else if (contentType == 2){
            [self.jmessageArray addObject:Jmessage];
            // 图片消息
            JMSGAbstractContent *content = Jmessage.content;

            JMSGImageContent *imgContent = (JMSGImageContent *)content;

//            NSLog(@"imgContent===%@",imgContent);
//            [imgContent thumbImageData:^(NSData *data, NSString *objectId, NSError *error) {

//                这里改变RunLoop模式
//                CFRunLoopStop(CFRunLoopGetMain());

//                if (data == nil || error) {
//
//                    NSLog(@"error===%@",error);
//
//                    return ;
//                }

//                UIImage * image = [UIImage imageWithData:data];

                [dict setObject:imgContent forKey:@"image"];

                NSString * timeStr = [NSString stringWithFormat:@"%@",Jmessage.timestamp];
                NSTimeInterval interval    = [timeStr doubleValue] / 1000;
                NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
                JMSGUser * user = Jmessage.fromUser;

                if (user.nickname) {
                    [dict setObject:user.nickname forKey:@"strName"];
                }

                [dict setObject:@(from) forKey:@"from"];
                [dict setObject:@(2) forKey:@"type"];
                [dict setObject:[date description] forKey:@"strTime"];
                [dict setObject:user forKey:@"user"];

                NSDictionary * dataDic = dict.copy;

                UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
                UUMessage * message = [[UUMessage alloc] init];
                [message setWithDict:dataDic];
                [message minuteOffSetStart:previousTime end:dataDic[@"strTime"]];
                messageFrame.showTime = message.showDateLabel;
                [messageFrame setMessage:message];

                if (message.showDateLabel) {
                    previousTime = dataDic[@"strTime"];
                }

                [result addObject:messageFrame];
//                NSLog(@"----------------");
//            }];
            
        }else if (contentType == 3){
            [self.jmessageArray addObject:Jmessage];
            // 语音消息
            JMSGAbstractContent *content = Jmessage.content;
            
            JMSGVoiceContent *voiceContent = (JMSGVoiceContent *)content;
            
            [voiceContent voiceData:^(NSData *data, NSString *objectId, NSError *error) {
                if (error == nil) {
                    
                    //这里改变RunLoop模式
//                    CFRunLoopStop(CFRunLoopGetMain());
                    //                        NSLog(@"data===%@",data);
                    [dict setObject:data forKey:@"voice"];
                    [dict setObject:voiceContent.duration forKey:@"strVoiceTime"];
                    
                    NSString * timeStr = [NSString stringWithFormat:@"%@",Jmessage.timestamp];
                    NSTimeInterval interval    = [timeStr doubleValue] / 1000;
                    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
                    JMSGUser * user = Jmessage.fromUser;
                    
                    if (user.nickname) {
                        [dict setObject:user.nickname forKey:@"strName"];
                    }
                    
                    [dict setObject:@(from) forKey:@"from"];
                    [dict setObject:@(3) forKey:@"type"];
                    [dict setObject:[date description] forKey:@"strTime"];
                    [dict setObject:user forKey:@"user"];
                    
                    NSDictionary * dataDic = dict.copy;
                    
                    UUMessageFrame *messageFrame = [[UUMessageFrame alloc]init];
                    UUMessage * message = [[UUMessage alloc] init];
                    [message setWithDict:dataDic];
                    [message minuteOffSetStart:previousTime end:dataDic[@"strTime"]];
                    messageFrame.showTime = message.showDateLabel;
                    [messageFrame setMessage:message];
                    
                    if (message.showDateLabel) {
                        previousTime = dataDic[@"strTime"];
                    }
                    
                    [result addObject:messageFrame];
                }
            }];
        }
    }
    
    //这里恢复RunLoop
//    CFRunLoopRun();
    return result;
    
}

// 如下:群聊（groupChat）
static int dateNum = 10;
- (NSDictionary *)getDic
{
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    int randomNum = arc4random()%5;
    if (randomNum == UUMessageTypePicture) {
        [dictionary setObject:[UIImage imageNamed:[NSString stringWithFormat:@"%u.jpeg",arc4random()%2]] forKey:@"picture"];
    } else {
        // 文字出现概率4倍于图片（暂不出现Voice类型）
        randomNum = UUMessageTypeText;
        [dictionary setObject:[self getRandomString] forKey:@"strContent"];
    }
    NSDate *date = [[NSDate date]dateByAddingTimeInterval:arc4random()%1000*(dateNum++) ];
    [dictionary setObject:@(UUMessageFromOther) forKey:@"from"];
    [dictionary setObject:@(randomNum) forKey:@"type"];
    [dictionary setObject:[date description] forKey:@"strTime"];
    // 这里判断是否是私人会话、群会话
    int index = _isGroupChat ? arc4random()%6 : 0;
    [dictionary setObject:[self getName:index] forKey:@"strName"];
    [dictionary setObject:[self getImageStr:index] forKey:@"strIcon"];
    
    return dictionary;
}

- (NSString *)getRandomString {
    
    NSString *lorumIpsum = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent non quam ac massa viverra semper. Maecenas mattis justo ac augue volutpat congue. Maecenas laoreet, nulla eu faucibus gravida, felis orci dictum risus, sed sodales sem eros eget risus. Morbi imperdiet sed diam et sodales.";
    
    NSArray *lorumIpsumArray = [lorumIpsum componentsSeparatedByString:@" "];
    
    int r = arc4random() % [lorumIpsumArray count];
    r = MAX(6, r); // no less than 6 words
    NSArray *lorumIpsumRandom = [lorumIpsumArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, r)]];
    
    return [NSString stringWithFormat:@"%@!!", [lorumIpsumRandom componentsJoinedByString:@" "]];
}

- (NSString *)getImageStr:(NSInteger)index{
    NSArray *array = @[@"http://www.120ask.com/static/upload/clinic/article/org/201311/201311061651418413.jpg",
                       @"http://p1.qqyou.com/touxiang/uploadpic/2011-3/20113212244659712.jpg",
                       @"http://www.qqzhi.com/uploadpic/2014-09-14/004638238.jpg",
                       @"http://e.hiphotos.baidu.com/image/pic/item/5ab5c9ea15ce36d3b104443639f33a87e950b1b0.jpg",
                       @"http://ts1.mm.bing.net/th?&id=JN.C21iqVw9uSuD2ZyxElpacA&w=300&h=300&c=0&pid=1.9&rs=0&p=0",
                       @"http://ts1.mm.bing.net/th?&id=JN.7g7SEYKd2MTNono6zVirpA&w=300&h=300&c=0&pid=1.9&rs=0&p=0"];
    return array[index];
}

- (NSString *)getName:(NSInteger)index{
    NSArray *array = @[@"Hi,Daniel",@"Hi,Juey",@"Hey,Jobs",@"Hey,Bob",@"Hah,Dane",@"Wow,Boss"];
    return array[index];
}
@end
